// webgroup
package webclient

import (
	"swim/util/nuid"
	//	"encoding/json"
	//	"fmt"
	//	"log"
	"net/http"
	"swim/etc"
	"swim/request"
	//	"strconv"
	"sync"
	"time"
)

type WebGroup struct {
	sync.Mutex
	Clients    map[string]*WebClient
	MaxClients int
	CurrentId  int
}

func NewWebGroup(max int) *WebGroup {
	group := new(WebGroup)
	group.Clients = make(map[string]*WebClient, max)
	group.MaxClients = max
	return group
}

/*
func (g *WebGroup) Broadcast(content string, fromId int) {
	for id, client := range g.Clients {
		if id == fromId {
			continue
		} else {
			client.Write(content)
		}
	}
}
*/
func (g *WebGroup) AddClient(w http.ResponseWriter,
	RemoteAddr string) *WebClient {
	if len(g.Clients) > g.MaxClients {
		return nil
	}
	g.Lock()
	g.CurrentId++
	c := new(WebClient)
	c.Id = nuid.TimeSeq()
	c.TmpName = c.Id
	c.SesionTickCount = time.Now()
	c.MsgPool = make(chan request.WebMsg, etc.SwImConfiger.MaxMsgPoolSize)
	c.w = w
	c.Ip = RemoteAddr
	g.Clients[c.Id] = c
	g.Unlock()
	//本可登录的
	return c
}

//clientId为web用户的会话ID
func (g *WebGroup) RemoveClient(clientId string) bool {
	c := g.Clients[clientId]
	if c == nil {
		return false
	}
	c.DelMsgKey()
	//c.On_Logout()
	g.Lock()
	delete(g.Clients, clientId)
	g.Unlock()
	return true
}

//clientId为web用户的会话ID
func (g *WebGroup) FindClient(clientId string) (*WebClient, bool) {
	c := g.Clients[clientId]
	if c == nil {
		return nil, false
	}
	//c.On_Logout()
	return c, true
}

func (g *WebGroup) StartGC() {
	go g.vaccuum()
	return
}

//check timeout
func (g *WebGroup) vaccuum() {

	for {
		<-time.After(etc.S_GC_SESSION_TIME * time.Second)
		if g.Clients == nil {
			return
		}
		for sid := range g.Clients {
			g.itemExpired(sid)
		}
	}

	return
}
func (g *WebGroup) itemExpired(sid string) bool {
	g.Lock()
	defer g.Unlock()

	itm, ok := g.Clients[sid]
	if !ok {
		return true
	}
	if itm.isExpire() {
		itm.DelMsgKey()
		delete(g.Clients, sid)
		return true
	}
	return false
}

/*
func (g *WebGroup) Sendto(formId, toId int, content string) {
	c := g.Clients[toId]
	if c == nil {
		log.Println("User[#%d] is bad.", toId)
		return
	}
	c.Write(fmt.Sprintf("msgfrom %d %s", formId, content))
}

func (g *WebGroup) GetClients() string {
	var jsonStr []byte
	names := make(map[string]UserInfo, len(g.Clients))
	i := 0
	for _, v := range g.Clients {
		id := strconv.Itoa(v.Id)
		names[id] = v.Info
		i++
	}
	jsonStr, err := json.Marshal(names)
	if err != nil {
		fmt.Println("error:", err)
	}
	return string(jsonStr)
}
*/
